package com.yu.mall.handle;

import com.yu.mall.constants.Constants;
import com.yu.mall.exception.ServiceException;
import com.yu.mall.util.ResultUtils;
import com.yu.mall.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;


@ControllerAdvice
@Slf4j
public class ExceptionHandle {
    private static final String ERROR_MSG = "系统异常";

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ResultVO handleMethodArgumentNotValidException(BindException exception) {
        StringBuilder errorInfos = new StringBuilder();
        BindingResult bindingResult = exception.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        if(!CollectionUtils.isEmpty(fieldErrors)){
            for (FieldError fieldError : fieldErrors) {
                errorInfos.append("错误参数：").append(fieldError.getField()).append("|")
                        .append("错误消息 ：").append(fieldError.getDefaultMessage()).append(";");
            }
        }
        String substring = errorInfos.substring(0, errorInfos.length() - 1);
        log.info(substring);
        return ResultUtils.error(Constants.VALID_ERROR_CODE,substring);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultVO handle(Exception e) {
        log.error("",e);
        if(e instanceof ServiceException){
            ServiceException serviceException = (ServiceException) e;
            ResultVO resultVO = ResultUtils.error(serviceException.getState(), serviceException.getMsg());
            return resultVO;
        }
        return ResultUtils.error(ERROR_MSG);
    }
}
